﻿using DAO.Repositories;
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication.Core.Helpers;
using WebApplication.Models;

namespace WebApplication
{
    public partial class Reports : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Dictionary<string, object> reportParameters = new Dictionary<string, object>();
            ReportSettingsModel reportSettings;

            if (Session["reportParameters"] == null)
                throw new InvalidOperationException("коллекция параметров отчета пуста");
            reportParameters = (Dictionary<string, object>)Session["reportParameters"];

            if (Session["reportsSettings"] == null)
                throw new InvalidOperationException("на заданы настройки отчета");
            reportSettings = (ReportSettingsModel)Session["reportsSettings"];

            List<Microsoft.Reporting.WebForms.ReportParameter> parameters = new List<Microsoft.Reporting.WebForms.ReportParameter>();

            foreach (var item in reportParameters.Keys)
            {
                Microsoft.Reporting.WebForms.ReportParameter p = new Microsoft.Reporting.WebForms.ReportParameter();
                p.Name = item;
                p.Values.Add(reportParameters[item].ToString());
                parameters.Add(p);
            }

            ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://alborozd/ReportServer_SQL12");
            ReportViewer1.ServerReport.ReportPath = "/DiplomReports/" + reportSettings.ReportPath;//"/DiplomReports/BestReport";
            
            //Microsoft.Reporting.WebForms.ReportParameter parameter = new ReportParameter();
            //parameter.Name = "IdServer";
            //parameter.Values.Add("1");

            ReportViewer1.ServerReport.SetParameters(parameters);
            ReportViewer1.ServerReport.Refresh();
            ReportViewer1.Visible = true;

            var notificationsRepository = new NotificationsRepository(new DAO.DeployAppEntities());

            if (!IsPostBack)
            {
                chklstUsers.DataSource = notificationsRepository.GetAll().Select(t => new { email = t.Email, name = t.Name });
                chklstUsers.DataBind();
            }
        }

        public byte[] Export(ReportViewer viewer, string exportType)//, string reportsTitle)
        {
            //try
            //{
                Warning[] warnings = null;
                string[] streamIds = null;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;
                string filetype = string.Empty;
                // just gets the Report title... make your own method
                //ReportViewer needs a specific type (not always the same as the extension)

                filetype = exportType == "PDF" ? "PDF" : exportType;
                byte[] bytes = viewer.ServerReport.Render(filetype, null, // deviceinfo not needed for csv
                out mimeType, out encoding, out extension, out streamIds, out warnings);
                //System.Web.HttpContext.Current.Response.Buffer = true;
                //System.Web.HttpContext.Current.Response.Clear();
                //System.Web.HttpContext.Current.Response.ContentType = mimeType;
                //System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + reportsTitle + "." + exportType);
                //System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
                
                //FileStream fs = new FileStream(Server.MapPath("~/GeneratedFiles/" + reportsTitle + "." + exportType), FileMode.OpenOrCreate);
                return bytes;
                //fs.Write(bytes, 0, bytes.Length);
                //fs.Close();

                // System.Web.HttpContext.Current.Response.Flush();
                // System.Web.HttpContext.Current.Response.End();
            //}
            //catch (Exception ex)
            //{
            //}
            //return true;
            
        }

        protected void btn_export_Click(object sender, EventArgs e)
        {
            string fileName = "TestReport";
           // byte[] exportFile = Export(ReportViewer1, DropDownList1.SelectedValue);//, "TestExport");

            switch (DropDownList1.SelectedValue)
            {
                case "PDF":
                    fileName += ".pdf";
                    break;
                case "Excel":
                    fileName += ".xls";
                    break;
                case "Word":
                    fileName += ".doc";
                    break;
            }

            Page.Response.Clear();
            Page.Response.ClearContent();
            Page.Response.ClearHeaders();
            Page.Response.HeaderEncoding = System.Text.Encoding.Default;
            Page.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            Page.Response.ContentType = "application/octet-stream";
            Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1251");
            byte[] buf = Export(ReportViewer1, DropDownList1.SelectedValue);
            Page.Response.AddHeader("Content-Length", buf.Length.ToString());
            Page.Response.BinaryWrite(buf);
            Page.Response.End();
        }

        protected void btnSubmitForUsers_Click(object sender, EventArgs e)
        {
            List<string> emails = new List<string>();

            for (int i = 0; i < chklstUsers.Items.Count; i++)
            {
                if (chklstUsers.Items[i].Selected)
                    emails.Add(chklstUsers.Items[i].Value);    
            }
            string subject = "Новый отчет";
            if (Session["reportsSettings"] != null)
                subject = ((ReportSettingsModel)Session["reportsSettings"]).ReportName;

            string reportExtention = ".pdf";
            switch (drpSubmit.SelectedValue)
            {
                case "PDF":
                    reportExtention = "pdf";
                    break;
                case "Excel":
                    reportExtention = "xls";
                    break;
                case "Word":
                    reportExtention = "doc";
                    break;
            }



            byte[] report = Export(ReportViewer1, drpSubmit.SelectedValue.ToString());

            string path = Server.MapPath("~/GeneratedFiles/" + subject + "." + reportExtention);
            if (File.Exists(path))
                File.Delete(path);
    
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            fs.Write(report, 0, report.Length);
            fs.Close();

            foreach (var email in emails)
            {
                if (Session["reportsSettings"] != null)
                    subject = ((ReportSettingsModel)Session["reportsSettings"]).ReportName;
                EmailSenderHelper.Send(EmailTextHelper.GetNewReportEmailText(),
                    email,
                    subject,
                    path);
            }
            
        }
    }
}